<template>
    <div>
        {{!-- 为什么需要在 dialog 关闭的时候销毁 dialog 中的元素？因为该 dialog 为详情表单，新增的时候会用到，编辑的时候也会用到，不销毁则需要增加代码做处理，例如需要监听当传入的 id，当变 id 更后，需要重新执行生命周期进行表单初始化，同时关闭 dialog 时还需要清空表单，避免出现再次打开 dialog 时表单还保留上一次的信息数据，当表单复杂度上去后，维护这块的成本过高，drawer 同理 --}}
        <el-dialog v-if="mode === 'dialog'" v-model="myVisible" :title="title" width="600px" :close-on-click-modal="false" append-to-body destroy-on-close>
            <DetailForm ref="form" v-bind="$props" />
            <template #footer>
                <el-button @click="onCancel">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </template>
        </el-dialog>
        <el-drawer v-else-if="mode === 'drawer'" v-model="myVisible" :title="title" size="600px" :close-on-click-modal="false" custom-class="form-mode-drawer" destroy-on-close>
            <DetailForm ref="form" v-bind="$props" class="form-container" />
            <div class="buttons">
                <el-button @click="onCancel">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import DetailForm from '../DetailForm/index.vue'

export default {
    components: {
        DetailForm
    },
    props: {
        ...DetailForm.props,
        modelValue: {
            default: false
        },
        mode: {
            default: 'dialog',
            validator: val => ['dialog', 'drawer'].includes(val)
        }
    },
    emits: ['update:modelValue', 'success'],
    computed: {
        myVisible: {
            get: function() {
                return this.modelValue
            },
            set: function(val) {
                this.$emit('update:modelValue', val)
            }
        },
        title() {
            return this.id == '' ? '新增{{ cname }}' : '编辑{{ cname }}'
        }
    },
    methods: {
        onSubmit() {
            // submit() 为组件内部方法
            this.$refs['form'].submit(() => {
                this.$emit('success')
                this.onCancel()
            })
        },
        onCancel() {
            this.myVisible = false
        }
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
    display: flex;
    flex-direction: column;
    overflow: auto;
}
.form-mode-drawer {
    .form-container {
        padding: 0 15px;
        overflow: auto;
        flex: 1;
    }
    .buttons {
        padding: 15px;
        text-align: right;
        background-color: #fff;
        border-top: 1px solid #ddd;
    }
}
</style>
